#include "writer.h"

Writer::Writer(Shell *shell, int timeout, QObject *parent)
    : QObject(parent)
    , QRunnable()
    , m_shell(shell)
    , m_timeout(timeout)
{
}

void Writer::run()
{
    int book = -1;
    do
    {
        emit i_m_waiting();
        ::sleep(m_timeout);
        book = m_shell->try_push_book();
        if (book != -1)
        {
            emit i_m_editing();
            m_books.push_back(book);
            emit i_m_waiting();
        }
    }
    while (book != -1);

    while (!m_books.empty()) // read while (true) if there are my books
    {
        int bookno = qrand() % m_books.size();
        int pos = m_books[bookno];
        m_shell->try_asquire_for_write(pos);
        emit i_m_editing();
        ::sleep(m_timeout);
        m_shell->release_book(pos);
        emit i_m_waiting();
    }
}

void Writer::set_timeout(int timeout)
{
    m_timeout = timeout;
}
